package src;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;


public class Log {
	ArrayList<Event> log;
	String logString;
	File file;
	FileWriter fstream;
	BufferedWriter out;
	
	public Log(int nodeid) throws IOException {
		log = new ArrayList<Event>();
		// Creates a separate log for each node since every machine on CSIL shares same files.  
		logString = "log"+nodeid+".txt";
		file = new File(logString);
		if(file.exists()) {
			fstream = new FileWriter(file, true);
		}
		else {
			fstream = new FileWriter(file);
		}
		
		out = new BufferedWriter(fstream);
	}
	
	public boolean logExists() {
		return file.exists();
	}
	
	public void addEvent(Event e) {
		log.add(e);
	}
	
	public void removeEvent(Event e) {
		if (log.indexOf(e)!= -1) {
			log.remove(e);
		}
	}

	
	public String toString() {
		String logString = "";
		Iterator logIterator = log.iterator();
		while(logIterator.hasNext()) {
			logString = logString + logIterator.next().toString();
		}
		return logString;
	}
	
	public void writeToFile(String event) {
		try{
		    out.append(event);
		    out.newLine();
		   
		    }
		
		catch (Exception e){
		      System.err.println("Error: " + e.getMessage());
		    }
	}
	
	public void closeLog() throws IOException {
		out.close();
	}
	
	public String readLog() {
		String log = "";
		StringBuffer contents = new StringBuffer();
		BufferedReader reader = null;
		
		try {
			reader = new BufferedReader(new FileReader(file));
			String logLine;
			while ((logLine = reader.readLine()) != null) {
				contents.append(logLine); //.append(System.getProperty("$"));
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (reader != null) {
					reader.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		log += contents.toString();
		//System.out.println(contents.toString());
		return log;
	}
	
	public int getSize() {
		return log.size();
	}
	
	public Event getEvent(int index) {
		return log.get(index);
	}

}
